<?php

namespace app\logic\platform;

use app\model\Shop;
use GuzzleHttp\Client;
use think\facade\Cache;

abstract class BasePlatform
{
    /**
     * 当前网店
     * @var Shop
    */
    protected $shop;

    /**
     * 请求客户端
     * @var Client
    */
    protected $client;

    /**
     * 计算出开始时间和结束时间
    */
    public function pullOrder(Shop $shop, Client $client) {
        $key = 'order_inc_pull_time_' . $shop->id;
        $this->shop = $shop;
        $last_time = Cache::get($key);
        $now_time = request()->time();
        $this->client = $client;
        //第一次拉取时间取两小时之前
        if (empty($last_time)) {
            $start_time = $now_time - 7200;
        } else {
            //从上次拉取事情往前推10分钟，防止误差
            $start_time = $last_time - 600;
        }
        $end_time = $now_time;

        $is_success = $this->pullProcess($start_time, $end_time);
        if ($is_success) {
            //更新商品拉取订单时间
            Cache::set($key, $now_time, 0);
        }
    }

    /**
     * 根据开始时间和结束时间开始下载订单
     * @param int $start_time 开始时间戳
     * @param int $end_time 结束时间戳
     * @return bool 是否下载成功
    */
    protected abstract function pullProcess(int $start_time, int $end_time) : bool;
}
